package com.ztil.socket.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Handler {

	private Socket _socket;
	private boolean _isConnection;

	public Handler(Socket socket) {
		this._socket = socket;
		this._isConnection = socket.isConnected() && !socket.isClosed(); //判断当前是否处于连接
		read();
		write();
	}

	public void read() {
		if (_isConnection) {
			new Thread(new Read(_socket)).start();
		}
	}

	public void write() {
		if (_isConnection) {
			new Thread(new Write(_socket)).start();
		}
	}

}

class Read implements Runnable {

	private Socket _readSocket;
	private BufferedReader _br;
	private String _result;

	public Read(Socket socket) {
		this._readSocket = socket;
		try {
			this._br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		try {
			while (null != (_result = _br.readLine())) {
				System.out.println(_readSocket.getRemoteSocketAddress() + "--->>>" + _result);
			}
		} catch (IOException e) {
			System.err.println("Client Reset : [" + _readSocket.getRemoteSocketAddress() + "]");
		}
	}
}

class Write implements Runnable {

	private Socket _writeSocket;
	private PrintWriter _pw;

	public Write(Socket socket) {
		this._writeSocket = socket;
		try {
			this._pw = new PrintWriter(_writeSocket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		while (true) {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String str;
			try {
				if (null != (str = br.readLine())) {
					_pw.println(str);
					_pw.flush();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
